package com.fast.common.web.advice;


import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.fast.common.constant.InterceptorConstant;
import com.fast.common.pojo.resp.Result;
import com.fast.common.web.annotation.ResponseResult;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

/**
 * 使用 @ControllerAdvice & ResponseBodyAdvice
 * 拦截Controller方法默认返回参数，统一处理返回值/响应体
 */
@RestController
@RestControllerAdvice
public class ResponseResultHandler implements ResponseBodyAdvice {


    // 判断是否要执行 beforeBodyWrite 方法，true为执行，false不执行，有注解标记的时候处理返回值
    @Override
    public boolean supports(MethodParameter methodParameter, Class aClass) {
        ServletRequestAttributes sra = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = sra.getRequest();
        // 判断请求是否有包装标记
        ResponseResult responseResultAnn = (ResponseResult) request.getAttribute(InterceptorConstant.RESPONSE_RESULT_ANN);
        return responseResultAnn != null;
    }

    // 对返回值做包装处理
    @Override
    public Object beforeBodyWrite(Object body, MethodParameter methodParameter, MediaType mediaType, Class aClass, ServerHttpRequest serverHttpRequest, ServerHttpResponse serverHttpResponse) {

        //处理返回字符串会报错的问题
        if (body instanceof String) {
            return JSON.toJSONString(Result.ok(body));
        }
        //可能为分页
        if (body instanceof IPage) {
            return Result.pagination((IPage) body);
        }
        //可能返回的就是带格式的
        if (body instanceof Result) {
            return body;
        }
        return Result.ok(body);
    }
}